import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';
import { CustomizedCouponService } from '../../services/customized-coupon.service';

@Component({
  selector: 'manual-release-modal',
  templateUrl: './manual-release-modal.component.html',
  styleUrls: ['./manual-release-modal.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ManualReleaseModalComponent),
      multi: true
    }
  ]
})
export class ManualReleaseModalComponent implements ControlValueAccessor, OnInit {

  @Input() modalTitle: string = '手动发放加价券';
  // @Input() submitLoading: boolean = false;
  @Input() couponCode!: number | string;
  @Output() submitManual = new EventEmitter();

  isViewVisible = false;
  submitLoading = false;
  _onChange: any = () => {};

  // 用户 Optios
  userTableParams: any = {
    userIds: [],
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 50,
    total: 0
  };

  isLoading = false;
  searchChange$ = new BehaviorSubject('');
  selectedUser?: Array<any>;

  constructor(
    private message: NzMessageService,
    private services: CustomizedCouponService
  ) { }

  ngOnInit(): void {
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        this.loadUserList(value)
      })
  }

  // 查询用户options
  async loadUserList(value?: any) {
    let params = {
      user: value || '',
      page: this.userTableParams.page,
      pageSize: this.userTableParams.pageSize
    }
    
    const res: any = await this.services.queryUserList(params);
    this.userTableParams.loading = false;
    this.isLoading = false;

    if (res.code === 0) {
      const { list, total } = res.data || {};
      this.userTableParams.tableData = this.userTableParams.tableData.concat(list);
      this.userTableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  loadUserMore() {
    if (this.userTableParams.tableData.length === this.userTableParams.total) {
      return
    }
    this.userTableParams.page += 1;
    this.userTableParams.loading = true;
    this.loadUserList();
  }

  onSearch(value: string): void {
    this.isLoading = true;
    this.userTableParams.page = 1;
    this.userTableParams.tableData = [];
    this.searchChange$.next(value);
  }

  selectChange(value: any) {
    this.userTableParams.userIds = value;
  }

  async subManual() {
    if (!this.userTableParams.userIds.length) {
      this.message.warning('请选择用户ID');
      return
    }
    let params = {
      couponNo: this.couponCode,
      userIdList: this.userTableParams.userIds
    }
    this.submitLoading = true;
    const {code, message}: any = await this.services.manualReleaseCoupon(params);
    this.submitLoading = false;

    if (code === 0) {
      this.message.success('发放成功');
      this.handleCancel();
      this.submitManual.emit(this.userTableParams.userIds);
    } else {
      this.message.error(message);
    }
  }

  handleCancel() {
    this.userTableParams.userIds = [];
    this.selectedUser = [];
    this.isViewVisible = false;
    this._onChange(false);
  }

  /**
   * ----------------------------------------------------------------
   * ngModel
   * ----------------------------------------------------------------
   */
  writeValue(val: any): void {
    if (val) {
      this.userTableParams.page = 1;
      this.userTableParams.tableData = [];
      this.userTableParams.userIds = [];
      this.loadUserList();
    }
    this.isViewVisible = val;
  }

  registerOnChange(fn: (_: any) => void): void {
    this._onChange = fn;
  }

  registerOnTouched(fn: any): void {}
}
